//
//  RecordAudioManager.m
//  RecorderView
//
//  Created by 明意 on 2021/7/21.
//  Copyright © 2021 Facebook. All rights reserved.
//

#import "RecordAudioManager.h"
#import "CustomRecorder.h"

@interface RecordAudioManager()

@property (nonatomic, strong) CustomRecorder *recorder;
@property (nonatomic, strong) CADisplayLink *displaylink;

@end

@implementation RecordAudioManager
{
    bool hasListeners;
}

RCT_EXPORT_MODULE();

- (dispatch_queue_t)methodQueue
{
  return dispatch_get_main_queue();
}

RCT_EXPORT_METHOD(start){
    if (!self.recorder){
        self.recorder = [[CustomRecorder alloc] init];
    }
    [self.recorder startRecord];
    [self startUpdatingMeter];
}

RCT_EXPORT_METHOD(stop:(RCTPromiseResolveBlock)resolve
                  rejecter:(__unused RCTPromiseRejectBlock)reject){

    [self.displaylink invalidate];
    self.displaylink = nil;

    [self.recorder stopRecord];

    resolve(self.recorder.filePath);

}

#pragma mark private
- (void)startUpdatingMeter {
    [self.displaylink invalidate];
    self.displaylink = nil;

    self.displaylink = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateMeters)];
    [self.displaylink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)updateMeters {
    CGFloat power = [self.recorder updateMeters];
//    [[NSNotificationCenter defaultCenter] postNotificationName:@"onRecorderAudioUpdateMeters" object:@{@"value": @(power)}];
    [self recordAudioEventReceived:power];
}

#pragma mark - events
// 在添加第一个监听函数时触发
-(void)startObserving {
    hasListeners = YES;
    // Set up any upstream listeners or background tasks as necessary
}

// Will be called when this module's last listener is removed, or on dealloc.
-(void)stopObserving {
    hasListeners = NO;
    // Remove upstream listeners, stop unnecessary background tasks
}
- (NSArray<NSString *> *)supportedEvents
{
  return @[@"onRecorderAudioUpdateMeters"];
}

- (void)calendarEventReminderReceived:(NSNotification *)notification
{
  NSString *eventName = notification.userInfo[@"value"];
  if (hasListeners) { // Only send events if anyone is listening
    [self sendEventWithName:@"onRecorderAudioUpdateMeters" body:@{@"value": eventName}];
  }
}

- (void)recordAudioEventReceived:(CGFloat)power
{
  if (hasListeners) { // Only send events if anyone is listening
    [self sendEventWithName:@"onRecorderAudioUpdateMeters" body:@{@"value": @(power)}];
  }
}

@end
